const {
  override, fixBabelImports, addLessLoader, addWebpackPlugin,
  addBundleVisualizer, overrideDevServer, addWebpackModuleRule,
  addWebpackAlias, addPostcssPlugins
} = require('customize-cra');

const path = require("path");

const PATHS = {
  src: path.join(__dirname, 'src'),
  appHtml: path.join(__dirname, 'public/index.html')
};

const rewireReactHotLoader = require('react-app-rewire-hot-loader');

//移除无用的css
const glob = require('glob-all');

const CompressionWebpackPlugin = require('compression-webpack-plugin');
// 打包配置
const addCustomize = () => config => {
  if (process.env.NODE_ENV === 'production') {
    // 添加js打包gzip配置
    config.plugins.push(
      new CompressionWebpackPlugin({
        test: /\.js$|\.jsx$|\.ts$|\.tsx$|\.css$/,
        threshold: 1024,
      }),
    )
  } else {
    config.devtool = 'cheap-module-source-map';
  }
  return config;
};

// 跨域配置
const devServerConfig = () => config => {
  return {
    ...config,
    // 服务开启gzip
    compress: true,
    // proxy: {
    //   '/api': {
    //     target: 'xxx',
    //     changeOrigin: true,
    //     pathRewrite: {
    //       '^/api': '/api',
    //     },
    //   }
    // }
  }
};

module.exports = {
  webpack: override(
    addCustomize(),

    // addBundleVisualizer({}, true),
    // fixBabelImports('import',
    //   {
    //     libraryName: 'antd',
    //     libraryDirectory: 'es',
    //     style: true,
    //   }
    // ),
    // fixBabelImports('import',
    //   {
    //     libraryName: 'react-use',
    //     libraryDirectory: 'lib',
    //     "camel2DashComponentName": false
    //   },
    // ),
    // fixBabelImports("lodash", {
    //   libraryDirectory: "",
    //   camel2DashComponentName: false
    // }),

    addLessLoader({
      javascriptEnabled: true,
      strictMath: true,
      noIeCompat: true,
      cssModules: {
        localIdentName: "[path][name]__[local]--[hash:base64:5]",
      },
      modifyVars: {
        // '@primary-color': '#036adf',
        // '@success-color': '#78b82e',
        // '@warning-color': '#fd7700',
        // '@black': '#333333'
      },
    }),
    addWebpackAlias({
      'react-dom': '@hot-loader/react-dom',
      '_components': path.resolve(__dirname, 'src/components'),
      '_pages': path.resolve(__dirname, 'src/pages'),
      '_libs': path.resolve(__dirname, 'src/libs'),
      '_src': path.resolve(__dirname, 'src'),
    }),
    ((config, env) => rewireReactHotLoader(config, env)),
    process.env.NODE_ENV === 'production' ? addPostcssPlugins([require("@fullhuman/postcss-purgecss")({
      content: [
        PATHS.appHtml,
        ...glob.sync(path.join(PATHS.src, '/**/*.{js,jsx,tsx}'), {nodir: true})],
    })]) : addPostcssPlugins([])
  ),
  devServer: overrideDevServer(
    devServerConfig()
  )
};
